package org.jeecg.modules.paycenter.channel.pufa;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.util.ConvertUtil;
import org.jeecg.common.util.HttpTools;
import org.jeecg.modules.wlhy.bill.entity.HyCarrierBill;
import org.jeecg.modules.wlhy.bill.entity.HyCustomerBill;
import org.jeecg.modules.wlhy.bill.entity.HyDriverBill;
import org.jeecg.modules.wlhy.bill.entity.HyShippingNoteBill;
import org.jeecg.modules.wlhy.bill.service.IHyCarrierBillService;
import org.jeecg.modules.wlhy.bill.service.IHyCustomerBillService;
import org.jeecg.modules.wlhy.bill.service.IHyDriverBillService;
import org.jeecg.modules.wlhy.bill.service.IHyShippingNoteBillService;
import org.jeecg.modules.wlhy.company.entity.HyCompany;
import org.jeecg.modules.wlhy.company.service.IHyCompanyService;
import org.jeecg.modules.wlhy.customer.entity.HyCustomer;
import org.jeecg.modules.wlhy.customer.service.IHyCustomerService;
import org.jeecg.modules.wlhy.hycarrier.entity.HyCarrier;
import org.jeecg.modules.wlhy.hycarrier.service.IHyCarrierService;
import org.jeecg.modules.wlhy.hydriver.entity.HyDriver;
import org.jeecg.modules.wlhy.hydriver.service.IHyDriverService;
import org.jeecg.modules.wlhy.hydriverbank.entity.HyDriverBank;
import org.jeecg.modules.wlhy.hydriverbank.service.IHyDriverBankService;
import org.jeecg.modules.wlhy.hypfaccount.entity.HyPfAccount;
import org.jeecg.modules.wlhy.hypfaccount.service.IHyPfAccountService;
import org.jeecg.modules.wlhy.utils.CodeUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;

@Service
@Slf4j
public class PfBankUtil {
    @Value(value = "${paycenter.url}")
    private String _baseUrl;

    @Autowired
    private IHyCustomerService hyCustomerService;

    @Autowired
    private IHyCompanyService hyCompanyService;
    @Autowired
    private IHyCarrierService hyCarrierService;
    @Autowired
    private IHyDriverService hyDriverService;

    @Autowired
    private IHyPfAccountService hyPfAccountService;

    @Autowired
    private IHyDriverBillService hyDriverBillService;
    @Autowired
    private IHyCarrierBillService hyCarrierBillService;

    @Autowired
    private IHyCustomerBillService hyCustomerBillService;

    @Autowired
    private IHyShippingNoteBillService hyShippingNoteBillService;

    @Autowired
    private IHyDriverBankService hyDriverBankService;

    public Result send(String url , String data) throws Exception {
        String ret  = HttpTools.postJson(url, data);
        return JSONObject.parseObject(ret,Result.class);
    }
    public Result editAcccount(HyPfAccount hyPfAccount) throws Exception {
        return send(_baseUrl + "/pf/editAcccount" ,JSONObject.toJSONString(hyPfAccount));
    }
    //创建货主子账号
    public Result createCustomerAcccount(HyPfAccount hyPfAccount , HyCustomer customer) throws Exception {

        String utype = hyPfAccount.getUtype();
        //交易席位号
        String bidsSnglFlgCd = CodeUtil.createDateNo(utype,5);
        hyPfAccount.setBidsSnglFlgCd(bidsSnglFlgCd);
        if("1".equals(customer.getCustomerType())){
            //个人
            String ctfId = customer.getIdcard();
            hyPfAccount.setCtfId(ctfId);
            hyPfAccount.setCtfType("1");
        }else {
            //公司
            String ctfId = customer.getCreditCode();//统一社会信用代码
            hyPfAccount.setCtfId(ctfId);
            hyPfAccount.setCtfType("2280");
        }
        return send(_baseUrl + "/pf/createAcccount" ,JSONObject.toJSONString(hyPfAccount));
    }
    public Result createCustomerAcccount(HyPfAccount hyPfAccount) throws Exception {

        if(StringUtils.isBlank(hyPfAccount.getOpenBranchName())){
            return Result.error("开户行名称不能为空！");
        }
        if(StringUtils.isBlank(hyPfAccount.getOpenBrNo())){
            return Result.error("开户行行号不能为空！");
        }
        if(StringUtils.isBlank(hyPfAccount.getBscAcctNo())){
            return Result.error("账户账号不能为空！");
        }
        if(StringUtils.isBlank(hyPfAccount.getAcctName())){
            return Result.error("账户名称不能为空！");
        }
        String uid = hyPfAccount.getUid();
        HyCustomer customer = hyCustomerService.getById(uid);
        if(customer == null){
            return Result.error("货主信息不存在！");
        }
        String utype = hyPfAccount.getUtype();
        //交易席位号
        String bidsSnglFlgCd = CodeUtil.createDateNo(utype,5);
        hyPfAccount.setBidsSnglFlgCd(bidsSnglFlgCd);

        if("1".equals(customer.getCustomerType())){
            //个人
            String ctfId = customer.getIdcard();
            hyPfAccount.setCtfId(ctfId);
            hyPfAccount.setCtfType("1");
        }else {
            //公司
            String ctfId = customer.getCreditCode();//统一社会信用代码
            hyPfAccount.setCtfId(ctfId);
            hyPfAccount.setCtfType("2280");
        }
        return send(_baseUrl + "/pf/createAcccount" ,JSONObject.toJSONString(hyPfAccount));
    }

    public Result createCompanyAcccount(HyPfAccount hyPfAccount) throws Exception {
        //分公司
        if(StringUtils.isBlank(hyPfAccount.getOpenBranchName())){
            return Result.error("开户行名称不能为空！");
        }
        if(StringUtils.isBlank(hyPfAccount.getOpenBrNo())){
            return Result.error("开户行行号不能为空！");
        }
        if(StringUtils.isBlank(hyPfAccount.getBscAcctNo())){
            return Result.error("账户账号不能为空！");
        }
        if(StringUtils.isBlank(hyPfAccount.getAcctName())){
            return Result.error("账户名称不能为空！");
        }
        String uid = hyPfAccount.getUid();
        HyCompany company = hyCompanyService.getById(uid);
        if(company == null){
            return Result.error("公司信息不存在！");
        }
        String utype = hyPfAccount.getUtype();
        //交易席位号
        String bidsSnglFlgCd = CodeUtil.createDateNo(utype,5);
        hyPfAccount.setBidsSnglFlgCd(bidsSnglFlgCd);

        hyPfAccount.setCtfId(company.getCreditCode());
        hyPfAccount.setCtfType("2280");
        log.info("-----开始进入浦发银行创建账号2");
        return send(_baseUrl + "/pf/createAcccount" ,JSONObject.toJSONString(hyPfAccount));
    }

    public Result createAcccount(HyPfAccount hyPfAccount) throws Exception {
        //交易席位号
        String bidsSnglFlgCd = CodeUtil.createDateNo(hyPfAccount.getUtype(),5);
        hyPfAccount.setBidsSnglFlgCd(bidsSnglFlgCd);
        return send(_baseUrl + "/pf/createAcccount" ,JSONObject.toJSONString(hyPfAccount));
    }

    public Result createCarrierAcccount(HyPfAccount hyPfAccount) throws Exception {
        //车队长
        String uid = hyPfAccount.getUid();
        HyCarrier carrier = hyCarrierService.getById(uid);
        if(carrier == null){
            return Result.error("车队长信息不存在！");
        }
        String idcard = carrier.getIdcard();
        if(StringUtils.isBlank(idcard)){
            return Result.error("开户人身份证号不能为空！");
        }
        String utype = hyPfAccount.getUtype();
        //交易席位号
        String bidsSnglFlgCd = CodeUtil.createDateNo(utype,5);
        hyPfAccount.setBidsSnglFlgCd(bidsSnglFlgCd);

        hyPfAccount.setCtfId(idcard);
        hyPfAccount.setCtfType("1");
        return send(_baseUrl + "/pf/createAcccount" ,JSONObject.toJSONString(hyPfAccount));
    }


    public Result createDriverAcccount(HyDriver driver) throws Exception {
        String idcard = driver.getIdcard();
        if (StringUtils.isBlank(idcard)) {
            return Result.error("身份证号不能为空！");
        }
        String utype = "4";
        String driverName = driver.getDriverName();
        HyPfAccount hyPfAccount = new HyPfAccount();
        hyPfAccount.setUtype(utype);
        hyPfAccount.setUid(driver.getId());
        hyPfAccount.setClientName(driverName);
        //交易席位号
        String bidsSnglFlgCd = CodeUtil.createDateNo(utype, 5);
        hyPfAccount.setBidsSnglFlgCd(bidsSnglFlgCd);

        hyPfAccount.setCtfId(idcard);
        hyPfAccount.setCtfType("1");
        hyPfAccount.setBscAcctNo("");
        hyPfAccount.setAcctName("");
        hyPfAccount.setOpenBranchName("");
        hyPfAccount.setOpenBrNo("");
        return send(_baseUrl + "/pf/createAcccount", JSONObject.toJSONString(hyPfAccount));
    }

    public Result createDriverAcccount(HyPfAccount hyPfAccount) throws Exception {
        String uid = hyPfAccount.getUid();
        HyDriver driver = hyDriverService.getById(uid);
        if(driver == null){
            return Result.error("司机信息不存在！");
        }
        String idcard = driver.getIdcard();
        if(StringUtils.isBlank(idcard)){
            return Result.error("身份证号不能为空！");
        }
        String utype = hyPfAccount.getUtype();
        //交易席位号
        String bidsSnglFlgCd = CodeUtil.createDateNo(utype,5);
        hyPfAccount.setBidsSnglFlgCd(bidsSnglFlgCd);

        hyPfAccount.setCtfId(idcard);
        hyPfAccount.setCtfType("1");
        return send(_baseUrl + "/pf/createAcccount" ,JSONObject.toJSONString(hyPfAccount));
    }

    public Result getChildAccountBalInfo(String childAcctNo) throws Exception{
        JSONObject jo = new JSONObject();
        jo.put("childAcctNo",childAcctNo);
        return send(_baseUrl + "/pf/getChildAccountBal" ,jo.toJSONString());
    }

    public void getChildAccountBalInfo(HyPfAccount account){
        try{
            Result ret = this.getChildAccountBalInfo(account.getChildAcctNo());
            if(ret.isSuccess()){
                JSONObject ret2 = (JSONObject) ret.getResult();
                String statusCode = ret2.getString("statusCode");
                if("0000".equals(statusCode)) {
                    account.setActualBal(ret2.getString("actualBal"));
                    account.setAmt(ret2.getString("amt"));
                    account.setFreezeAmt(ret2.getString("freezeAmt"));
                    account.setStatusCode(statusCode);
                    account.setStatusMsg("正常");
                }else {
                    String statusMsg = ret2.getString("statusMsg");
                    account.setActualBal("0.00");
                    account.setAmt("0.00");
                    account.setFreezeAmt("0.00");
                    account.setStatusCode(statusCode);
                    account.setStatusMsg(statusMsg);
                }
            }else {
                account.setActualBal("0.00");
                account.setAmt("0.00");
                account.setFreezeAmt("0.00");
                account.setStatusCode("-99");
                account.setStatusMsg(ret.getMessage());
            }
        }catch (Exception e){
            account.setActualBal("0.00");
            account.setAmt("0.00");
            account.setFreezeAmt("0.00");
            account.setStatusCode("-99");
            account.setStatusMsg(e.getMessage());
        }
    }

    public BigDecimal getChildAccountBal(String childAcctNo){
        try {
            Result ret = getChildAccountBalInfo(childAcctNo);
            if(ret.isSuccess()){
                JSONObject ret2 = (JSONObject) ret.getResult();
                String statusCode = ret2.getString("statusCode");
                if("0000".equals(statusCode)) {
                    String actualBal = ret2.getString("actualBal");
                    return new BigDecimal(actualBal);
                }
                return null;
            }
        }catch (Exception e){

        }
        return null;
    }

    public Result<?> driverBindBank(HyDriverBank driverBank) throws Exception {
        return send(_baseUrl + "/pf/driver/bindAcctNo", JSONObject.toJSONString(driverBank));
    }

    public Result<?> driverTx(HyDriver driver, JSONObject jd) throws Exception {
        log.info("开始进入司机提现");
        String driverBankId =  jd.getString("driverBankId");
        if(StringUtils.isEmpty(driverBankId)){
            return Result.error("银行卡不能为空！");
        }
        String amt = jd.getString("amt");
        if(!ConvertUtil.isMoney(amt)){
            return Result.error("提现金额不正确！");
        }

        //验证卡号
        HyDriverBank driverBank = hyDriverBankService.getById(driverBankId);
        if(driverBank == null){
            return Result.error("未获取到银行卡信息！");
        }
        if(!StringUtils.equals( driverBank.getDriverId() ,driver.getId())){
            return Result.error("银行卡信息错误！");
        }
        String bankName = driverBank.getBankName();
        if(!StringUtils.equals(bankName,driver.getDriverName())){
            return Result.error("银行卡必须是本人！");
        }
        HyPfAccount account = hyPfAccountService.getDriverAccount(driver.getId());
        if(account == null) {
            return Result.error("未开通钱包");
        }

//        if("0".equals(driverBank.getIzPf())){
//            //绑定银行卡
//            Result<?> result = this.driverBindBank(driverBank);
//            if(!result.isSuccess()){
//                return result;
//            }
//        }
        String bankNum = driverBank.getBankNum();

        JSONObject data = new JSONObject();
        String channelSeqNoNum = CodeUtil.getChannelSeqNoNum();
        data.put("channelSeqNo",channelSeqNoNum);//商户交易流水号
        data.put("capitalAcctNo",account.getChildAcctNo());//子账号
        data.put("authrCd",account.getAuthrCd());
        data.put("opnBnkNm","其他银行");//收款方开户行名称
        data.put("openBrNo","9999");//收款方开户行行号
        data.put("pyAcctNm",bankName);//收款方户名
        data.put("pyAcctNo",bankNum);//收款方账号
        data.put("tranAmt",amt);//交易金额
        data.put("remark","司机提现");//备注
        Result ret = send(_baseUrl + "/pf/tx", data.toJSONString());
        log.info("司机提现结果为：{}", ret.toString());
        if(ret.isSuccess()){
            JSONObject ret2 = (JSONObject) ret.getResult();
            String tranSeqNo = ret2.getString("tranSeqNo");
            //保存司机提现流水单
            HyDriverBill driverBill = new HyDriverBill();
            driverBill.setBillNum(tranSeqNo);
            driverBill.setBillType("2");//提现
            driverBill.setDriverId(driver.getId());
            driverBill.setDbaccno(account.getChildAcctNo());
            driverBill.setDbaccname(account.getChildAcctNm());
            driverBill.setDblogaccno("");
            driverBill.setCraccno(bankNum);
            driverBill.setCraccname(bankName);
            driverBill.setCrlogaccno("");
            driverBill.setAmt(new BigDecimal(amt)); //提现金额
            driverBill.setRespSource("0");
            driverBill.setRespCode("4");
            driverBill.setRespInfo("交易成功");
            driverBill.setRxtInfo(channelSeqNoNum);
            driverBill.setPayChannel(PfBankService.CHANNEL);
            hyDriverBillService.save(driverBill);
            return Result.OK("提现成功");
        }
        return ret;
    }

    public Result<?> carrierTx(HyCarrier carrier ,HyPfAccount account, String amt) throws Exception {
        JSONObject data = new JSONObject();
        String channelSeqNoNum = CodeUtil.getChannelSeqNoNum();
        data.put("channelSeqNo",channelSeqNoNum);//商户交易流水号
        data.put("capitalAcctNo",account.getChildAcctNo());//子账号
        data.put("authrCd",account.getAuthrCd());
        data.put("opnBnkNm","其他银行");//收款方开户行名称
        data.put("openBrNo","9999");//收款方开户行行号
        data.put("pyAcctNm",account.getAcctName());//收款方户名
        data.put("pyAcctNo",account.getBscAcctNo());//收款方账号
        data.put("tranAmt",amt);//交易金额
        data.put("remark","车队长提现");//备注
        Result ret = send(_baseUrl + "/pf/tx", data.toJSONString());
        if(ret.isSuccess()){
            JSONObject ret2 = (JSONObject) ret.getResult();
            String tranSeqNo = ret2.getString("tranSeqNo");
            //保存车队长提现流水单
            HyCarrierBill carrierBill = new HyCarrierBill();
            carrierBill.setBillNum(tranSeqNo);
            carrierBill.setBillType("2");//提现
            carrierBill.setCarrierId(carrier.getId());
            carrierBill.setDbaccno(account.getChildAcctNo());
            carrierBill.setDbaccname(account.getChildAcctNm());
            carrierBill.setDblogaccno("");
            carrierBill.setDbProv("");
            carrierBill.setCraccno(account.getBscAcctNo());
            carrierBill.setCraccname(account.getAcctName());
            carrierBill.setCrlogaccno("");
            carrierBill.setCrBankCode("");
            carrierBill.setAmt(new BigDecimal(amt)); //提现金额
            carrierBill.setPayChannel(PfBankService.CHANNEL);
            carrierBill.setRespSource("0");
            carrierBill.setRespCode("4");
            carrierBill.setRespInfo("交易成功");
            carrierBill.setRxtInfo(channelSeqNoNum);
            hyCarrierBillService.save(carrierBill);
            return Result.OK("提现成功");
        }
        return ret;
    }


    public Result<?> customerTx(HyCustomer customer, HyPfAccount account, String amt) throws Exception {
        JSONObject data = new JSONObject();
        String channelSeqNoNum = CodeUtil.getChannelSeqNoNum();
        data.put("channelSeqNo",channelSeqNoNum);//商户交易流水号
        data.put("capitalAcctNo",account.getChildAcctNo());//子账号
        data.put("authrCd",account.getAuthrCd());
        data.put("opnBnkNm", account.getOpenBranchName());//收款方开户行名称
        data.put("openBrNo",account.getOpenBrNo());//收款方开户行行号
        data.put("pyAcctNm",account.getAcctName());//收款方户名
        data.put("pyAcctNo",account.getBscAcctNo());//收款方账号
        data.put("tranAmt",amt);//交易金额
        data.put("remark","货主提现");//备注
        Result ret = send(_baseUrl + "/pf/tx", data.toJSONString());
        if(ret.isSuccess()){
            JSONObject ret2 = (JSONObject) ret.getResult();
            String tranSeqNo = ret2.getString("tranSeqNo");

            HyCustomerBill bill = new HyCustomerBill();
            bill.setBillNum(tranSeqNo);
            bill.setBillType("3");//提现
            bill.setCustomerId(customer.getId());
            bill.setDbaccno(account.getChildAcctNo());
            bill.setDbaccname(account.getChildAcctNm());
            bill.setDblogaccno("");
            bill.setDbProv("");
            bill.setCraccno(account.getBscAcctNo());
            bill.setCraccname(account.getAcctName());
            bill.setCrlogaccno("");
            bill.setAmt(new BigDecimal(amt)); //提现金额
            bill.setPayChannel(PfBankService.CHANNEL);
            bill.setRespSource("0");
            bill.setRespCode("4");
            bill.setRespInfo("交易成功");
            bill.setRxtInfo(channelSeqNoNum);
            hyCustomerBillService.save(bill);
            return Result.OK("提现成功");
        }
        return ret;
    }

    public Result<?> companyTx(HyPfAccount account, String amt) throws Exception {
        JSONObject data = new JSONObject();
        String channelSeqNoNum = CodeUtil.getChannelSeqNoNum();
        data.put("channelSeqNo",channelSeqNoNum);//商户交易流水号
        data.put("capitalAcctNo",account.getChildAcctNo());//子账号
        data.put("authrCd",account.getAuthrCd());
        data.put("opnBnkNm", account.getOpenBranchName());//收款方开户行名称
        data.put("openBrNo",account.getOpenBrNo());//收款方开户行行号
        data.put("pyAcctNm",account.getAcctName());//收款方户名
        data.put("pyAcctNo",account.getBscAcctNo());//收款方账号
        data.put("tranAmt",amt);//交易金额
        data.put("remark","货主提现");//备注
        Result ret = send(_baseUrl + "/pf/tx", data.toJSONString());
        if(ret.isSuccess()){
            return Result.OK("提现成功");
        }
        return ret;
    }

    public Result<?> downloadCustomerBillHd(HyCustomerBill customerBill , String bidsSnglFlgCd){
        try {
            JSONObject jo = new JSONObject();
            jo.put("snglFlgCd", customerBill.getRxtInfo());//bussType=07,  互转交易流水号 hostflw
            jo.put("rmYll", bidsSnglFlgCd);//交易席位号
            //        00-资金代发单笔回单　
            //        01-资金代发批次回单
            //        03-资金代发批次单笔回单
            //        04-资金代发日终单笔回单
            //        05-入金单笔回单（暂仅支持灵活用工业务使用）
            //        06-出金单笔回单（暂仅支持灵活用工业务使用）
            //        07-子账户互转单笔回
            jo.put("bussType","07");
            jo.put("billNum", customerBill.getBillNum());//流水单号
            Result ret = send(_baseUrl + "/pf/downLoadHd", jo.toJSONString());
            if(ret.isSuccess()){
                customerBill.setBankHdFu(ret.getResult().toString());
                hyCustomerBillService.updateById(customerBill);
            }
            return ret;
        }catch (Exception e){
            return Result.error(e.getMessage());
        }
    }

    public Result<?> downloadCompanyBillHd(HyShippingNoteBill bill, String bidsSnglFlgCd) {
        try {
            JSONObject jo = new JSONObject();
            jo.put("snglFlgCd", bill.getRxtInfo());//bussType=07,  互转交易流水号 hostflw
            jo.put("rmYll", bidsSnglFlgCd);//交易席位号
            //        00-资金代发单笔回单　
            //        01-资金代发批次回单
            //        03-资金代发批次单笔回单
            //        04-资金代发日终单笔回单
            //        05-入金单笔回单（暂仅支持灵活用工业务使用）
            //        06-出金单笔回单（暂仅支持灵活用工业务使用）
            //        07-子账户互转单笔回
            jo.put("bussType","07");
            jo.put("billNum", bill.getShippingNoteNumber());//运单号
            Result ret = send(_baseUrl + "/pf/downLoadHd", jo.toJSONString());
            if(ret.isSuccess()){
                bill.setBankHd(ret.getResult().toString());
                hyShippingNoteBillService.updateById(bill);
            }
            return ret;
        }catch (Exception e){
            return Result.error(e.getMessage());
        }
    }

    //查询交易明细
    public Result<?> getTransInfosList(JSONObject data) {
        try {
            Result ret = send(_baseUrl + "/pf/getTransInfosList", data.toJSONString());
            return ret;
        }catch (Exception e){
            return Result.error(e.getMessage());
        }
    }

    public Result<?> downloadCustomerRjHd(String ylkTranSeqNo, String bidsSnglFlgCd) {
        try {
            JSONObject jo = new JSONObject();
            jo.put("snglFlgCd", ylkTranSeqNo);//bussType=05,  核心交易流水号 ylkTranSeqNo
            jo.put("rmYll", bidsSnglFlgCd);//交易席位号
            //        00-资金代发单笔回单　
            //        01-资金代发批次回单
            //        03-资金代发批次单笔回单
            //        04-资金代发日终单笔回单
            //        05-入金单笔回单（暂仅支持灵活用工业务使用）
            //        06-出金单笔回单（暂仅支持灵活用工业务使用）
            //        07-子账户互转单笔回
            jo.put("bussType","05");
            jo.put("billNum", ylkTranSeqNo);
            Result ret = send(_baseUrl + "/pf/downLoadRjHd", jo.toJSONString());
            return ret;
        }catch (Exception e){
            return Result.error(e.getMessage());
        }
    }
}
